<template>
  <CDialog
    :title="title"
    :close-on-click-modal="false"
    v-model:visible="dialogVisible"
    size="large"
    @cancel="handleClose"
    @confirm="handleConfirm"
    :confirm-text="readonly ? '关闭' : '保存'"
    :showCancelButton="!readonly"
  >
    <div class="form-dialog-container" v-loading="loading">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-position="top"
        :disabled="readonly"
        hide-required-asterisk
      >
        <SubTitle title="年度碳盘查">
          <template #right v-if="!readonly">
            <el-button
              type="primary"
              @click="handleSyncInventoryData"
              :loading="syncLoading"
              v-btnPermission="'TAA_VIEW_INSPECT_SYNC_INVENTORY'"
              >同步盘查数据</el-button
            >
          </template>
        </SubTitle>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排放单位" prop="organizationCode">
              <CSelect v-model="formData.organizationCode" placeholder="请选择" :disabled="isEdit">
                <el-option
                  v-for="item in organizationBoundarOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </CSelect>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年份" prop="dischargeYear">
              <el-date-picker
                type="year"
                format="YYYY"
                value-format="YYYY"
                v-model="formData.dischargeYear"
                placeholder="请输入"
                clearable
                :disabled="isEdit"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6"> </el-col>
          <el-col :span="6">
            <el-form-item label="年度产量" prop="yield">
              <el-input
                v-model="formData.yield"
                placeholder="请输入"
                v-number-valid="{
                  digit: 6,
                  canNegative: true
                }"
                clearable
                ><template #suffix>台</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产天数" prop="workDay">
              <el-input
                v-model="formData.workDay"
                placeholder="请输入"
                v-number-valid="{
                  digit: 6,
                  canNegative: true
                }"
                clearable
                ><template #suffix>天</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="碳盘查排放量" prop="carbonInventoryEmission">
              <el-input
                v-model="formData.carbonInventoryEmission"
                placeholder="请输入"
                v-number-valid="{
                  digit: 6,
                  canNegative: true
                }"
                clearable
              >
                <template #suffix>tCO₂</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘查日期" prop="inventoryDate">
              <el-date-picker
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                v-model="formData.inventoryDate"
                placeholder="请输入"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <SubTitle title="年度碳核查" border />
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="碳核查排放量" prop="carbonInspectEmission">
              <el-input
                v-model="formData.carbonInspectEmission"
                placeholder="请输入"
                v-number-valid="{
                  digit: 6,
                  canNegative: true
                }"
                clearable
              >
                <template #suffix>tCO₂</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="核查日期" prop="inspectDate">
              <el-date-picker
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                v-model="formData.inspectDate"
                placeholder="请输入"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="碳核查机构" prop="inspectDepartment">
              <el-input
                v-model="formData.inspectDepartment"
                placeholder="请输入"
                maxlength="20"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <SubTitle title="配额发放预测" border>
          <template #right v-if="!readonly">
            <el-button
              type="primary"
              @click="handleForecastQuotaData"
              :loading="forecastLoading"
              v-btnPermission="'TAA_VIEW_INSPECT_QUOTA_FORECAST'"
              >配额预测</el-button
            >
          </template>
        </SubTitle>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="配额分配方法" prop="quotaDistributionType">
              <CSelect v-model="formData.quotaDistributionType" placeholder="请选择">
                <el-option
                  v-for="item in QuotaDistributionTypeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </CSelect>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年度调节系数" prop="annualAdjustmentCoefficient">
              <el-input
                v-model="formData.annualAdjustmentCoefficient"
                placeholder="请输入"
                v-number-valid="{
                  digit: 6,
                  canNegative: true
                }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="历史三年基准值" prop="historyBenchmarkData">
              <el-input
                v-model="formData.historyBenchmarkData"
                placeholder="请输入"
                v-number-valid="{
                  digit: 6,
                  canNegative: true
                }"
                clearable
              >
                <template #suffix>tCO₂/天</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年度配额计算" prop="annualQuotaCalculate">
              <el-input
                v-model="formData.annualQuotaCalculate"
                placeholder="请输入"
                v-number-valid="{
                  digit: 6,
                  canNegative: true
                }"
                clearable
              >
                <template #suffix>tCO₂</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="配额缺口" prop="quotaGap">
              <el-input
                v-model="formData.quotaGap"
                placeholder="请输入"
                v-number-valid="{
                  digit: 6,
                  canNegative: true
                }"
                clearable
                ><template #suffix>tCO₂</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="缺口/核查量占比" prop="gapProportion">
              <el-input
                v-model="formData.gapProportion"
                placeholder="请输入"
                v-number-valid="{
                  digit: 2,
                  canNegative: false
                }"
                clearable
              >
                <template #suffix>%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年度配额应发" prop="annualQuotaGrant">
              <el-input
                v-model="formData.annualQuotaGrant"
                placeholder="请输入"
                v-number-valid="{
                  digit: 6,
                  canNegative: true
                }"
                clearable
              >
                <template #suffix>tCO₂</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </CDialog>
</template>
<script lang="ts" setup name="AddOrEditLowCarbonMaterial">
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { CSelect } from '@/components/CSelect';
import type { GetInspectListResult } from '@/apis/taa/asset/model/inspectModel';
import {
  postCreateCarbonInspect,
  postEditCarbonInspect,
  postSyncInventoryData,
  postQuotaForecastData,
  getChildByCodeList
} from '@/apis/taa/asset/inspect';
import { useMessage } from '@/hooks/useMessage';
import { QuotaDistributionTypeOption, QuotaDistributionTypeEnum } from '@/constants/enum';
import SubTitle from './SubTitle.vue';
import { rules } from './rules';
import { isNullOrUnDef } from '@/utils/is';
import { rateToNumber, numberToRate } from '@/utils';

interface CSetEmissionFactorDialogProps {
  visible: boolean;
  loading?: boolean;
  tempRow?: GetInspectListResult;
  // eslint-disable-next-line no-undef
  dischargeUnitOption: LabelValueOptions;
  // 是否是详情页
  readonly?: boolean;
}
const props = withDefaults(defineProps<CSetEmissionFactorDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh']);
const { createMessage } = useMessage();
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});

watch(
  () => props.visible,
  val => {
    if (val) {
      init();
      getOrganizationBoundarOptions();
    }
  }
);
const isEdit = computed(() => {
  return props.tempRow && props.tempRow.inspectNo && !props.readonly;
});
const readonly = computed(() => {
  return props.readonly;
});
const title = computed(() => {
  return (readonly.value ? '查看' : isEdit.value ? '编辑' : '新增') + '核查记录';
});

const formRef = ref();
const loading = ref(false);
const formData = reactive({
  inspectNo: '',
  organizationCode: '',
  dischargeYear: '',
  yield: '',
  workDay: '',
  carbonInventoryEmission: '',
  inventoryDate: '',

  carbonInspectEmission: '',
  inspectDate: '',
  inspectDepartment: '',

  quotaDistributionType:
    'HISTORICAL_TOTAL_EMISSION_REDUCTION' as keyof typeof QuotaDistributionTypeEnum,
  annualAdjustmentCoefficient: '1',
  historyBenchmarkData: '',
  annualQuotaCalculate: '',
  quotaGap: '',
  gapProportion: '',
  annualQuotaGrant: ''
});

async function init() {
  if (props.tempRow && props.tempRow.inspectNo) {
    formData.inspectNo = props.tempRow.inspectNo;
    formData.organizationCode = props.tempRow.organizationCode;
    formData.dischargeYear = props.tempRow.dischargeYear;
    formData.yield = props.tempRow.yield;
    formData.workDay = props.tempRow.workDay;
    formData.carbonInventoryEmission = String(props.tempRow.carbonInventoryEmission ?? '');
    formData.inventoryDate = props.tempRow.inventoryDate;
    formData.carbonInspectEmission = String(props.tempRow.carbonInspectEmission ?? '');
    formData.inspectDate = props.tempRow.inspectDate;
    formData.inspectDepartment = props.tempRow.inspectDepartment;
    formData.quotaDistributionType =
      props.tempRow.quotaDistributionType ?? 'HISTORICAL_TOTAL_EMISSION_REDUCTION';
    formData.annualAdjustmentCoefficient = String(props.tempRow.annualAdjustmentCoefficient ?? '1');
    formData.historyBenchmarkData = String(props.tempRow.historyBenchmarkData ?? '');
    formData.annualQuotaCalculate = String(props.tempRow.annualQuotaCalculate ?? '');
    formData.quotaGap = String(props.tempRow.quotaGap ?? '');
    formData.gapProportion = String(rateToNumber(props.tempRow.gapProportion) ?? '');
    formData.annualQuotaGrant = String(props.tempRow.annualQuotaGrant ?? '');
  } else {
    formData.inspectNo = '';
    formData.organizationCode = '';
    formData.dischargeYear = '';
    formData.yield = '';
    formData.workDay = '';
    formData.carbonInventoryEmission = '';
    formData.inventoryDate = '';
    formData.carbonInspectEmission = '';
    formData.inspectDate = '';
    formData.inspectDepartment = '';
    formData.quotaDistributionType = 'HISTORICAL_TOTAL_EMISSION_REDUCTION';
    formData.annualAdjustmentCoefficient = '1';
    formData.historyBenchmarkData = '';
    formData.annualQuotaCalculate = '';
    formData.quotaGap = '';
    formData.gapProportion = '';
    formData.annualQuotaGrant = '';
  }
}

/**
 * 同步盘查数据
 */
const syncLoading = ref(false);
async function handleSyncInventoryData() {
  if (!(formData.organizationCode && formData.dischargeYear)) {
    createMessage.error('请先完善单位及年份！');
    return;
  }
  try {
    syncLoading.value = true;
    const params = {
      organizationCode: formData.organizationCode,
      dischargeYear: formData.dischargeYear
    };
    const res = await postSyncInventoryData(params);
    formData.inventoryDate = res?.inventoryDate;
    formData.yield = res?.yield;
    formData.workDay = res?.workDay;
    formData.carbonInventoryEmission = res?.carbonInventoryEmission;
    createMessage.success('同步盘查数据成功！');
    syncLoading.value = false;
  } catch (error) {
    console.log('error', error);
    // createMessage.error('同步盘查数据失败！');
    syncLoading.value = false;
  }
}

/**
 * 配额预测
 */
const forecastLoading = ref(false);
async function handleForecastQuotaData() {
  if (
    !(
      formData.organizationCode &&
      formData.dischargeYear &&
      formData.yield &&
      formData.workDay &&
      formData.carbonInventoryEmission
    )
  ) {
    createMessage.error('请先完善年度碳盘查信息！');
    return;
  }
  if (!formData.carbonInspectEmission) {
    createMessage.error('请先完善碳核查排放量！');
    return;
  }
  if (!formData.quotaDistributionType) {
    createMessage.error('请先选择配额分配方法！');
    return;
  }
  if (!formData.annualAdjustmentCoefficient) {
    createMessage.error('请先完善年度调节系数！');
    return;
  }
  try {
    forecastLoading.value = true;
    const params = {
      organizationCode: formData.organizationCode,
      dischargeYear: formData.dischargeYear,
      yield: formData.yield,
      workDay: formData.workDay,
      carbonInspectEmission: Number(formData.carbonInspectEmission),
      quotaDistributionType: formData.quotaDistributionType,
      annualAdjustmentCoefficient: Number(formData.annualAdjustmentCoefficient),
      carbonInventoryEmission: Number(formData.carbonInventoryEmission)
    };
    const res = await postQuotaForecastData(params);
    formData.historyBenchmarkData = String(res.historyBenchmarkData);
    formData.annualQuotaCalculate = String(res.annualQuotaCalculate);
    formData.quotaGap = String(res.quotaGap);
    formData.gapProportion = String(rateToNumber(res.gapProportion));
    formData.annualQuotaGrant = String(res.annualQuotaGrant);
    createMessage.success('配额预测成功！');
    forecastLoading.value = false;
  } catch (error) {
    console.log('error', error);
    // createMessage.error('配额预测失败！');
    forecastLoading.value = false;
  }
}

/**
 * 获取提交的值
 */
function getSubmitValue(value: any, isRate = false) {
  // 如果是null或者undefine
  if (isNullOrUnDef(value)) return null;
  // 空字符串
  if (typeof value === 'string' && value.trim() === '') return null;
  // 数字或者字符串类型的数字
  if (typeof value === 'number' || !isNaN(Number(value))) {
    if (isRate) return numberToRate(Number(value), 4);
    return Number(value);
  }
  // 其他类型的都不传
  return null;
}

function handleConfirm() {
  if (readonly.value) return handleClose();
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const params = {
          ...formData,
          carbonInventoryEmission: getSubmitValue(formData.carbonInventoryEmission),
          carbonInspectEmission: getSubmitValue(formData.carbonInspectEmission),
          annualAdjustmentCoefficient: getSubmitValue(formData.annualAdjustmentCoefficient),
          historyBenchmarkData: getSubmitValue(formData.historyBenchmarkData),
          annualQuotaCalculate: getSubmitValue(formData.annualQuotaCalculate),
          quotaGap: getSubmitValue(formData.quotaGap),
          gapProportion: getSubmitValue(formData.gapProportion, true),
          annualQuotaGrant: getSubmitValue(formData.annualQuotaGrant)
        };
        console.log('handleConfirm params', params);
        loading.value = true;
        if (isEdit.value) {
          await postEditCarbonInspect(params);
          createMessage.success('编辑核查记录成功！');
        } else {
          await postCreateCarbonInspect(params);
          createMessage.success('新增核查记录成功！');
        }
        loading.value = false;
        emits('refresh');
        handleClose();
      } catch (error) {
        loading.value = false;
        console.log('error', error);
      }
    }
  });
}

// eslint-disable-next-line no-undef
const organizationBoundarOptions = ref<LabelValueOptions>([]);
function getOrganizationBoundarOptions(v?: string) {
  getChildByCodeList(v).then(res => {
    organizationBoundarOptions.value = res
      .filter(item => item.tag === 'FACTORY') // 先过滤出tag为'FACTORY'的项
      .map(item => ({
        value: item.organizationCode,
        label: item.organizationName
      }));
  });
}

function handleClose() {
  dialogVisible.value = false;
}
</script>
